package mytaxis.move.model;

import java.util.Calendar;
import java.util.TimeZone;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class MyTaxisModel {

	MyTaxisDB ssdb;
	SQLiteDatabase db;

	public MyTaxisModel(Context context) {
		ssdb = new MyTaxisDB(context, "MyTaxisDB", null, 1);
		db = ssdb.getWritableDatabase();
	}

	public Cursor getTasksMonth(int monthStart, int monthEnd, int yearStart,
			int yearEnd, int days, boolean filterStatus, String statusFiltered) {
		db = ssdb.getWritableDatabase();
		Calendar cal = Calendar.getInstance();
		cal.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
		cal.set(Calendar.MONTH, monthStart);
		cal.set(Calendar.YEAR, yearStart);
		cal.set(Calendar.DAY_OF_MONTH, 1);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		String timeStart = String.valueOf(cal.getTimeInMillis() / 1000);
		cal.set(Calendar.MONTH, monthEnd);
		cal.set(Calendar.YEAR, yearEnd);
		cal.set(Calendar.DAY_OF_MONTH, days);
		cal.set(Calendar.HOUR_OF_DAY, 23);
		cal.set(Calendar.MINUTE, 59);
		cal.set(Calendar.SECOND, 59);
		String timeEnd = String.valueOf(cal.getTimeInMillis() / 1000);
		String where = "(datahora>? AND datahora<?)";
		if (filterStatus)
			where = where + " AND estat=?";
		String[] selectArgs = new String[2 + intValue(filterStatus)];
		selectArgs[0] = timeStart;
		selectArgs[1] = timeEnd;
		if (filterStatus)
			selectArgs[2] = statusFiltered;
		String orderBy = "datahora ASC";
		Cursor c = db.query("Tasca", null, where, selectArgs, null, null,
				orderBy);
		return c;
	}

	private int intValue(boolean b) {
		return b ? 1 : 0;
	}

	public Cursor getTasksDay(int day, int month, int year,
			boolean filterStatus, String statusFiltered) {
		db = ssdb.getWritableDatabase();
		Calendar cal = Calendar.getInstance();
		cal.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
		cal.set(Calendar.MONTH, month);
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.DAY_OF_MONTH, day);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		String timeStart = String.valueOf(cal.getTimeInMillis() / 1000);
		cal.set(Calendar.HOUR_OF_DAY, 23);
		cal.set(Calendar.MINUTE, 59);
		cal.set(Calendar.SECOND, 59);
		String timeEnd = String.valueOf(cal.getTimeInMillis() / 1000);
		String[] selectArgs = new String[2 + intValue(filterStatus)];
		selectArgs[0] = timeStart;
		selectArgs[1] = timeEnd;
		if (filterStatus)
			selectArgs[2] = statusFiltered;
		String where = "(datahora>? AND datahora<?)";
		if (filterStatus)
			where = where + " AND estat=?";
		String orderBy = "datahora ASC";
		Cursor c = db.query("Tasca", null, where, selectArgs, null, null,
				orderBy);
		return c;
	}

	public long getNowTime() {
		Calendar cal = Calendar.getInstance();
		cal.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
		cal.set(Calendar.SECOND, cal.get(Calendar.SECOND));
		cal.set(Calendar.MINUTE, cal.get(Calendar.MINUTE));
		cal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY));
		cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH));
		cal.set(Calendar.MONTH, cal.get(Calendar.MONTH));
		cal.set(Calendar.YEAR, cal.get(Calendar.YEAR));
		return cal.getTimeInMillis() / 1000;
	}

	public void closeDB() {
		db.close();
	}

	public void updateStatus(String id, String status) {
		db.execSQL("UPDATE Tasca SET estat='" + status + "' WHERE _id='" + id
				+ "';");
	}
	
	public boolean taskExists(String id) {
		Cursor c = db.query("Tasca", null, "_id=?", new String[]{id}, null, null,null);
		if(c.moveToFirst()){
			c.close();
			return true;
		}
		c.close();
		return pendingTaskExists(id);
	}
	
	public boolean pendingTaskExists(String id) {
		Cursor c = db.query("TascaPendent", null, "_id=?", new String[]{id}, null, null,null);
		if(c.moveToFirst()){
			c.close();
			return true;
		}
		c.close();
		return false;
	}

	public void insertPendingRequest(String id, String posX, String posY, String dia, String hora, String address) {
		long now = getNowTime();
		String datahora = dia.substring(1,dia.length()-1)+" "+hora.substring(1, hora.length()-1);
		db.execSQL("INSERT INTO TascaPendent (_id, datahorastring, ubicacio, longitud, latitud, datarebut) VALUES ("+id+
				",'"+datahora+"','"+address+"',"+posX+","+posY+","+now+");");
	}

	public Cursor getPendingTasks() {
		return db.query("TascaPendent", null, null, null, null, null,null);
	}

	public void deletePendingRequest(String id) {
		db.execSQL("DELETE FROM TascaPendent WHERE _id="+id+";");
	}

	public void acceptPendingRequest(Cursor taskClicked) {
		String dateString = taskClicked.getString(1);
		String dateAndHour[] = dateString.split(" ");
		String[] dateFields = dateAndHour[0].split("-");
		String[] hourFields = dateAndHour[1].split(":");
		Calendar cal = Calendar.getInstance();
		cal.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
		cal.set(Calendar.MONTH, Integer.parseInt(dateFields[1])-1);
		cal.set(Calendar.YEAR, Integer.parseInt(dateFields[2]));
		cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(dateFields[0]));
		cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hourFields[0]));
		cal.set(Calendar.MINUTE, Integer.parseInt(hourFields[1]));
		cal.set(Calendar.SECOND, 0);
		Log.d("calendar",cal.toString());
		long time = cal.getTimeInMillis()/1000;
		db.execSQL("INSERT INTO Tasca (_id, datahora, datahorastring, estat, ubicacio, longitud, latitud) VALUES ("+
				taskClicked.getString(0)+","+time+",'"+taskClicked.getString(1)+"','Scheduled','"+taskClicked.getString(2)+
				"',"+taskClicked.getDouble(3)+","+taskClicked.getDouble(4)+");");
		deletePendingRequest(taskClicked.getString(0));
	}

	public Cursor getIdTimePendings() {
		return db.query("TascaPendent", new String[]{"_id","datarebut"}, null, null, null, null,null);
	}

	public Cursor getTasksWithAnotherId(String[] ids) {
		if(ids==null){
			return db.query("Tasca", new String[]{"_id"}, "estat=?", new String[]{"Scheduled"}, null, null,null);
		}
		else{
			String[] values = new String[ids.length+1];
			String inParams = "(";
			for(int i=0; i<ids.length; i++){
				values[i] = ids[i];
				if(i==ids.length-1) inParams=inParams+"?)";
				else inParams=inParams+"?,";
			}
			values[ids.length] = "Scheduled";
			return db.query("Tasca", new String[]{"_id"}, "_id NOT IN "+inParams+" AND estat=?", values, null, null,null);
		}
	}

	public Cursor getPendingTasksWithAnotherId(String[] ids) {
		if(ids==null){
			return db.query("Tasca", new String[]{"_id"}, null, null, null, null,null);
		}
		else{
			String[] values = new String[ids.length];
			String inParams = "(";
			for(int i=0; i<ids.length; i++){
				values[i] = ids[i];
				if(i==ids.length-1) inParams=inParams+"?)";
				else inParams=inParams+"?,";
			}
			return db.query("TascaPendent", new String[]{"_id"}, "_id NOT IN "+inParams, values, null, null,null);
		}
	}

}
